package com.spider.im.chat.message.massage;

import com.google.protobuf.Parser;
import com.spider.im.chat.annotation.MessageTypeHandler;
import com.spider.im.chat.message.AbstractMessageStrategy;
import com.spider.im.chat.proto.ChatProto;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

@Component
@Slf4j
@MessageTypeHandler(type = ChatProto.MessageType.PRIVATE_CHAT)
public class PrivateChatStrategy extends AbstractMessageStrategy<ChatProto.PrivateChatRequest> {


    @Override
    public Parser<ChatProto.PrivateChatRequest> getParser() {
        return ChatProto.PrivateChatRequest.parser();
    }

    @Override
    public void handle(ChannelHandlerContext ctx, ChatProto.PrivateChatRequest message) {

        log.info("发送私聊消息: {}", message.getMessage());
        long receiver = message.getReceiver();
        Channel channel = activeChannels.get(receiver);
        boolean success = false;
        String messageR = "消息发送成功";

        if (channel == null || !channel.isActive()) {
            log.error("用户:{}不在线", receiver);
            messageR = "用户"+receiver +"不在线";
            ChatProto.MessageWrapper wrapper = getMessageWrapper(success,messageR);
            this.sendResponse(ctx.channel(), wrapper);
            return;
        }
        ChatProto.MessageWrapper wrapperMessage = getMessageWrapper(true, message.getMessage());
        // 发送消息
        this.sendResponse(channel, wrapperMessage);
        success = true;
        ChatProto.MessageWrapper wrapper = getMessageWrapper(success,messageR);
        this.sendResponse(ctx.channel(), wrapper);
    }

    /**
     * 构建消息包装
     *
     * @return
     */
    private static ChatProto.MessageWrapper getMessageWrapper(boolean success, String message) {
        ChatProto.Response response = ChatProto.Response.newBuilder()
                .setSuccess(success)
                .setMessage(message)
                .build();
        return ChatProto.MessageWrapper.newBuilder()
                .setType(ChatProto.MessageType.PRIVATE_CHAT)
                .setPayload(response.toByteString())
                .build();
    }
}
